package com.free.web.controller.system.controller;

import com.free.common.annotation.Log;
import com.free.common.core.controller.BaseController;
import com.free.common.core.domain.AjaxResult;
import com.free.common.core.page.TableDataInfo;
import com.free.common.core.text.Convert;
import com.free.common.enums.BusinessType;
import com.free.common.utils.DateUtils;
import com.free.common.utils.StringUtils;
import com.free.common.utils.poi.ExcelUtil;
import com.free.quartz.domain.SysJob;
import com.free.quartz.service.ISysJobService;
import com.free.system.domain.FreeMember;
import com.free.system.domain.FreeTicket;
import com.free.system.domain.FreeTicketClickTask;
import com.free.system.mapper.FreeMemberMapper;
import com.free.system.mapper.FreeTicketMapper;
import com.free.system.service.IFreeTicketClickTaskService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 票券定时触发Controller
 *
 * @author Sophia
 * @date 2025-02-27
 */
@Controller
@RequestMapping("/system/task")
public class FreeTicketClickTaskController extends BaseController {
    private String prefix = "system/task";

    @Autowired
    private IFreeTicketClickTaskService freeTicketClickTaskService;
    @Autowired
    private FreeMemberMapper freeMemberMapper;
    @Autowired
    private FreeTicketMapper freeTicketMapper;
    @Autowired
    private ISysJobService sysJobService;

    @RequiresPermissions("system:task:view")
    @GetMapping()
    public String task() {
        return prefix + "/task";
    }

    /**
     * 查询票券定时触发列表
     */
    @RequiresPermissions("system:task:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(FreeTicketClickTask freeTicketClickTask) {
        startPage();
        List<FreeTicketClickTask> list = freeTicketClickTaskService.selectFreeTicketClickTaskList(freeTicketClickTask);
        return getDataTable(list);
    }

    /**
     * 导出票券定时触发列表
     */
    @RequiresPermissions("system:task:export")
    @Log(title = "票券定时触发", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(FreeTicketClickTask freeTicketClickTask) {
        List<FreeTicketClickTask> list = freeTicketClickTaskService.selectFreeTicketClickTaskList(freeTicketClickTask);
        ExcelUtil<FreeTicketClickTask> util = new ExcelUtil<FreeTicketClickTask>(FreeTicketClickTask.class);
        return util.exportExcel(list, "票券定时触发数据");
    }

    /**
     * 新增票券定时触发
     */
    @RequiresPermissions("system:task:add")
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存票券定时触发
     */
    @RequiresPermissions("system:task:add")
    @Log(title = "票券定时触发", businessType = BusinessType.INSERT)
    @PostMapping("/addOld")
    @ResponseBody
    public AjaxResult addSave(FreeTicketClickTask freeTicketClickTask) {
        return toAjax(freeTicketClickTaskService.insertFreeTicketClickTask(freeTicketClickTask));
    }

    /**
     * 修改票券定时触发
     */
    @RequiresPermissions("system:task:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        FreeTicketClickTask freeTicketClickTask = freeTicketClickTaskService.selectFreeTicketClickTaskById(id);
        mmap.put("freeTicketClickTask", freeTicketClickTask);
        return prefix + "/edit";
    }

    /**
     * 修改保存票券定时触发
     */
    @RequiresPermissions("system:task:edit")
    @Log(title = "票券定时触发", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(FreeTicketClickTask freeTicketClickTask) {
        return toAjax(freeTicketClickTaskService.updateFreeTicketClickTask(freeTicketClickTask));
    }

    /**
     * 删除票券定时触发
     */
    @RequiresPermissions("system:task:remove")
    @Log(title = "票券定时触发", businessType = BusinessType.DELETE)
    @PostMapping("/removeOld")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(freeTicketClickTaskService.deleteFreeTicketClickTaskByIds(ids));
    }

    /**
     * 新增保存票券定时触发
     */
    @RequiresPermissions("system:task:add")
    @Log(title = "票券定时触发", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addTaskSave(FreeTicketClickTask freeTicketClickTask) {
        // 1.获取票券id和会员id后再入库
        FreeMember freeMember = freeMemberMapper.selectFreeMemberById(freeTicketClickTask.getMemberId());
        freeTicketClickTask.setMemberPhone(freeMember.getMemberPhone());
        FreeTicket freeTicket = freeTicketMapper.selectFreeTicketById(freeTicketClickTask.getTicketId());
        freeTicketClickTask.setTicketName(freeTicket.getTicketName());
        freeTicketClickTask.setCreateTime(DateUtils.getNowDate());
        // TODO 入库成功后job_id和明细url需要设置下
        // 先起任务后入库
        Long takeHour = freeTicket.getTakeHour();
        Long takeMinute = freeTicket.getTakeMinute();
        String invokeTarget = String.format("ryTask.taskGetTicketByPhone('%s', '%s', %s, %s)",
                freeMember.getMemberPhone(),
                freeTicket.getTicketName(),
                takeHour,
                takeMinute);
        Long beforeMinuteClick = freeTicket.getBeforeMinuteClick();
        Long clickHour = takeHour;
        Long clickMinute = takeMinute;
        if (takeMinute < beforeMinuteClick) {
            clickHour -= 1;
            clickMinute = 60 + (takeMinute - beforeMinuteClick);
        } else {
            clickMinute = (takeMinute - beforeMinuteClick);
        }

        // 0 59 9 * * ?
        // 秒 分 时
        String cronExpression = String.format("0 %s %s * * ?", clickMinute, clickHour);
        SysJob job = new SysJob();
        job.setJobName(freeTicketClickTask.getJobName());
        job.setJobGroup("DEFAULT");
        job.setInvokeTarget(invokeTarget);
        job.setCronExpression(cronExpression);
        job.setMisfirePolicy("1");
        job.setConcurrent("1");
        job.setStatus("0"); // 启用
        job.setRemark(freeTicketClickTask.getJobName() + "-定时任务");
        try {
            sysJobService.insertJobCustom(job);
            freeTicketClickTask.setJobId(job.getJobId());
            freeTicketClickTask.setJobDetail("/monitor/jobLog?jobId=" + job.getJobId());
            freeTicketClickTask.setJobStatus("正常");
            return toAjax(freeTicketClickTaskService.insertFreeTicketClickTask(freeTicketClickTask));
        } catch (Exception e) {
            logger.error("新建定时任务出现异常：{}", e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return toAjax(false);
    }

    /**
     * 删除票券定时触发
     */
    @RequiresPermissions("system:task:remove")
    @Log(title = "票券定时触发", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult removeTask(String ids) {
        if (StringUtils.isNotBlank(ids)) {
            String[] idArr = Convert.toStrArray(ids);
            for (String id : idArr) {
                FreeTicketClickTask task = freeTicketClickTaskService.selectFreeTicketClickTaskById(Long.valueOf(id));
                try {
                    sysJobService.deleteJobByIds(String.valueOf(task.getJobId()));
                } catch (SchedulerException e) {
                    logger.error("删除定时任务时出现异常：{}", e.getMessage());
                    logger.error(e.getMessage(), e);
                }
            }
            return toAjax(freeTicketClickTaskService.deleteFreeTicketClickTaskByIds(ids));
        }
        return toAjax(false);
    }


}
